// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: wsfuyibing <682805@qq.com>
// Date: 2024-08-20

package gen_annotation

import (
	_ "embed"
	"fmt"
)

//go:embed template_middleware.tpl
var templateMiddleware string

// SeekerMiddleware
// is a component for middleware files manager.
type SeekerMiddleware struct {
	Seeker *Seeker

	result *ResultMiddleware
	target string
}

// Add
// adds a middleware file resource to manager.
func (o *SeekerMiddleware) Add(resource *Resource) (err error) {
	return resource.Reader(o.Seeker.Provider, o)
}

// Do
// generate and save to target file.
func (o *SeekerMiddleware) Do() (err error) {
	err = o.Seeker.Save(o.result.Ready(), o.target, templateMiddleware)
	return
}

// Match
// matches the line text of a resource file.
func (o *SeekerMiddleware) Match(resource *Resource, comment *Comment, line int, text string) (err error) {
	var (
		entity *EntityMiddleware
		match  []string
	)

	// Match
	// text string and return if not match on middleware.
	if match = ResourceRegexMatchMiddleware.FindStringSubmatch(text); len(match) == 0 {
		return
	}

	// Creates
	// a new entity.
	entity = NewEntityMiddleware(match[1])
	entity.Import = resource.Import
	entity.Package = resource.Package
	entity.File = fmt.Sprintf(`%s/%s`, resource.Path, resource.Src)
	entity.Line = line

	// Use
	// annotation name.
	if list := comment.GetAnnotation(AnnotationName); list != nil {
		for _, x := range list {
			if s := x.First(); s != "" {
				entity.Name = s
				break
			}
		}
	}

	// Success found.
	o.result.AddEntity(entity)
	o.Seeker.Container.GetOutput().Info(`  - found: source="%s/%s:%d", handler="%s", name="%s"`, resource.Path, resource.Src, line, entity.Func, entity.Name)
	return
}

// Target
// returns a file path for generated content.
func (o *SeekerMiddleware) Target() string { return o.target }

// +---------------------------------------------------------------------------+
// | Access methods                                                            |
// +---------------------------------------------------------------------------+

func (o *SeekerMiddleware) init() *SeekerMiddleware {
	o.result = NewResultMiddleware(o.Seeker.Command, o.Seeker.Provider.AnnotationPkg)
	o.target = fmt.Sprintf(`%s/%s/annotation_middlewares.go`, o.Seeker.Provider.WorkingDir, o.Seeker.Provider.AnnotationPath)
	o.Seeker.Container.GetOutput().Info(`+ [scanner:middleware] %s`, o.target)
	return o
}
